/*
 * main.c
 *
 *  Created on: 08.06.2011
 *      Author: alexs
 */

#include <avr/io.h>
#include "stk500protocol.h"
#include <avr/boot.h>
#define USARTBAUD 38400L

//void (*nullVector)(void) __attribute__ ((naked)) __attribute__((__noreturn__));

void nullVector(void) __attribute__ ((naked));
void nullVector(void) {
	asm volatile ("eor r30,r30\n\tmov r31,r30\n\tijmp\n\t"::);
}


void hw_init(void) __attribute__ ((naked)) __attribute__ ((section (".init3")));
void hw_init() {
	UCSR0A=(1<<U2X0)|(1<<TXC0);
	UCSR0B=(1<<RXEN0)|(1<<TXEN0);
	UCSR0C=(1<<UCSZ01)|(1<<UCSZ00);
	UBRR0L=(uint8_t)(F_CPU / (8L * USARTBAUD) -1);

	ICR1L=0xff;
	TCCR1B=(1<<WGM12)|(1<<WGM13)|(1<<CS12)|(1<<CS10);
	TIFR1=0xff;
	UDR0='\n';
	if ((boot_lock_fuse_bits_get(GET_LOCK_BITS)&0x3f)!=0x0c) boot_lock_bits_set(~0x0c);
	while (!(UCSR0A&(1<<RXC0))) { if (TIFR1) nullVector(); }
	if (UDR0!='B') nullVector();
}
int main(void) __attribute__ ((naked)) __attribute__((__noreturn__));
int main(void){
	UDR0='b';
	while ((UCSR0A&(1<<UDRE0))==0) {};
	UDR0='\n';
	ICR1=600;
	DDRD|=(1<<PD5)|(1<<PD6);
	PORTD|=(1<<PD5);
	for (;;) {
		if (TIFR1&0x07) {
			PIND|=(1<<PD5)|(1<<PD6);
			TIFR1=0xff;
		}
		if (UCSR0A&(1<<RXC0)) {
			stk_buff_add(UDR0);
		}
	}
}
